<?php


namespace App\Http\Controllers\Chat;


use App\Http\Controllers\Controller;
use App\Models\ChatMessage;
use App\Models\ChatRoom;
use App\Models\ChatRoomUser;
use App\Models\User;
use Illuminate\Http\Request;

class ChatRoomController extends Controller
{
    public function index(Request $request)
    {
        $user_id = $request->user()->id;
        $data = ChatRoomUser::where('user_id', $user_id)->get();
        foreach ($data as $item){
            $item->friend = ChatRoomUser::with(['user'])->where('room_id', $item->room_id)->where('user_id', '<>', $user_id)->first();
            $item->last_message = ChatMessage::where('room_id', $item->room_id)->orderBy('created_at','desc')->first();
            $item->unread_num = ChatMessage::where('room_id', $item->room_id)->where('id', '>', $item->read_message_id)->count();
        }
        return $this->response($data);
    }

    public function store(Request $request, ChatRoom $obj)
    {
        $obj->type = 0;
        $obj->save();
        ChatRoomUser::insert([
            ['user_id' => $request->input('fid'), 'room_id' => $obj->id],
            ['user_id' => $request->user()->id, 'room_id' => $obj->id],
        ]);
        $id = $obj->id;
        $friend = User::where('id', $request->input('fid'))->first();
        return $this->response(compact('id', 'friend'));
    }

}
